package com.glodon.paas.account.security.oauth1.service;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import net.oauth.OAuth;
import net.oauth.OAuthAccessor;
import net.oauth.OAuthMessage;
import net.oauth.OAuthProblemException;
import net.oauth.server.OAuthServlet;

import com.glodon.paas.account.security.oauth1.provider.SimpleOAuthProvider;

/**
 * @author Don Li
 */
public class AccessTokenServlet extends HttpServlet {
    
	@Autowired
	private SimpleOAuthProvider oauthProvider;
	
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
	}
	
	@Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        processRequest(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        processRequest(request, response);
    }

    public void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        try {
            OAuthMessage requestMessage = OAuthServlet.getMessage(request, null);
            OAuthAccessor accessor = oauthProvider.getAccessor(requestMessage); // get accessor
            oauthProvider.VALIDATOR.validateMessage(requestMessage, accessor); // validate accessor

            // make sure token is authorized
            if (!Boolean.TRUE.equals(accessor.getProperty("authorized"))) {
                throw new OAuthProblemException("permission_denied");
            }
            // generate access token and secret
            oauthProvider.generateAccessToken(accessor);
            // write token/secret to response
            response.setContentType("text/plain");
            OutputStream out = response.getOutputStream();
            OAuth.formEncode(OAuth.newList("oauth_token", accessor.accessToken, "oauth_token_secret", accessor.tokenSecret), out);
            out.close();
        } catch (Exception e) {
        	oauthProvider.handleException(e, request, response, true);
        }
    }
}
